package com.zhs.gccs.view.gccs;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.annimon.stream.Stream;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.zhs.gccs.R;
import com.zhs.gccs.dao.TaskGccjFileDao;
import com.zhs.gccs.model.AcFileTemp;
import com.zhs.gccs.model.CaData;
import com.zhs.gccs.model.CaDict;
import com.zhs.gccs.model.CaDictDataVo;
import com.zhs.gccs.model.CaFile;
import com.zhs.gccs.model.CaForm;
import com.zhs.gccs.model.CjFile;
import com.zhs.gccs.model.SmTask;
import com.zhs.gccs.model.StatisticsDict;
import com.zhs.gccs.model.TaskProject;
import com.zhs.gccs.utils.DialogUtils;
import com.zhs.gccs.utils.JsonParser;
import com.zhs.gccs.utils.OnNoDoubleClickListener;
import com.zhs.gccs.utils.PermissionConstants;
import com.zhs.gccs.utils.PermissionUtils;
import com.zhs.gccs.utils.SoftKeyboardUtils;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.utils.Utils;
import com.zhs.gccs.view.BaseView;
import com.zhs.gccs.view.LocationAddress;
import com.zhs.gccs.view.taskMap.GccjTakeImageView;

import java.util.List;

//工程措施抽检
public class TaskGccsDataFormView extends BaseView {

    private GccjTakeImageView take_image;
    private GccjTakeImageView take_video;//
    private TextView tv_location;//位置
    private EditText et_input_remarks;//备注
    private RadioButton rb_fh;//抽检结果符合
    private RadioButton rb_bfh;//抽检结果不符合
    private String cjjgsffh = "1";//符合1(默认) 不符合0

    private TextView tv_speech;
    ///////////////////////////////
    private Activity activity;
    TaskProject taskProject;
    SmTask smTask;
    StatisticsDict caType;
    StatisticsDict currentLevel;
    private View ll_btns;
    private View btn_save;
    private View btn_cancel;
    LocationAddress location;
    CaForm caForm;
    private List<CaDict> dictsOfForm;
    private CaData data;//表单数据
    ///////////////////////////////////////

    private TaskGccjFileDao taskGccjFileDao;
    public TaskGccsDataFormView(@NonNull Context context) {
        super(context);
    }

    public TaskGccsDataFormView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TaskGccsDataFormView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void init(Context context, AttributeSet attrs, int defStyleAttr) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_view_task_gccs_data_form, this, true);
//        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomerLogo);
//        String title = typedArray.getString(R.styleable.CustomerInfoItem_preText);
//        typedArray.recycle();
        taskGccjFileDao = new TaskGccjFileDao();
        take_image = view.findViewById(R.id.take_image);
        take_video = view.findViewById(R.id.take_video);
        tv_location = view.findViewById(R.id.tv_location);
        et_input_remarks = view.findViewById(R.id.et_input_remarks);
        rb_fh = view.findViewById(R.id.rb_fh);
        rb_bfh = view.findViewById(R.id.rb_bfh);
        cjjgsffh = "1";
        rb_fh.setChecked(true);
        rb_fh.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)cjjgsffh = "1";
            }
        });
        rb_bfh.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)cjjgsffh = "0";
            }
        });


        ll_btns = view.findViewById(R.id.ll_btns);
        btn_save = view.findViewById(R.id.btn_save);
        btn_cancel = view.findViewById(R.id.btn_cancel);
        btn_save.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                SoftKeyboardUtils.hideSoftInput(activity);
                CaDictDataVo dictDataVo = new CaDictDataVo();
                dictDataVo.setDictId(currentLevel.getDictId());
                dictDataVo.setTaskId(smTask.getTaskid());
                dictDataVo.setPid(taskProject.getpId());
                if(data!=null){
                    //修改---不能修改位置---但是必须传这些参数---统一校验了
                    dictDataVo.setDataId(data.getId());
                    dictDataVo.setAddress(data.getAddress());
                    dictDataVo.setLatitude(data.getLatitude()+"");
                    dictDataVo.setLongitude(data.getLongitude()+"");
                }
                dictDataVo.setCjjg(cjjgsffh);
                dictDataVo.setRemarks(et_input_remarks.getText().toString().trim());
                if(dataFormListener!=null){
                    dataFormListener.onSave(taskProject,smTask,
                            caType,currentLevel,
                            dictDataVo,
                            take_image.getPhotos(),
                            take_video.getPhotos());
                }
            }
        });
        btn_cancel.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                SoftKeyboardUtils.hideSoftInput(activity);
                DialogUtils.showPromote2(context, "确定取消，不保存?", null, new DialogUtils.OnConfirmListener() {
                    @Override
                    public void onConfirmed() {
                        if(dataFormListener!=null)dataFormListener.onCancel();
                    }
                });
            }
        });
        tv_speech = view.findViewById(R.id.tv_speech);
        tv_speech.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                speech();
            }
        });
    }

    public void speech() {
        requestSpeechPermission();
    }

    private void requestSpeechPermission() {
        PermissionUtils.permission(PermissionConstants.MICROPHONE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(ShouldRequest shouldRequest) {
                        DialogUtils.showPromote2(context, "请开启权限", new DialogUtils.OnCancelListener() {
                            @Override
                            public void onCanceled() {
                                shouldRequest.again(false);
                            }
                        }, new DialogUtils.OnConfirmListener() {
                            @Override
                            public void onConfirmed() {
                                shouldRequest.again(true);
                            }
                        });
                    }
                }).callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        toSpeech();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogUtils.showOpenAppSettingDialog(context);
                            return;
                        }
                        requestSpeechPermission();
                    }
                }).request();
    }

    private void toSpeech() {
        //1.创建RecognizerDialog对象
        RecognizerDialog mDialog = new RecognizerDialog(context, null);
        //2.设置accent、language等参数
        mDialog.setParameter(SpeechConstant.PARAMS, null);//清空参数
        mDialog.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置听写引擎
        mDialog.setParameter(SpeechConstant.RESULT_TYPE, "json");// 设置返回结果格式
        mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");// 设置语言
        mDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mDialog.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mDialog.setParameter(SpeechConstant.VAD_EOS, "3000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mDialog.setParameter(SpeechConstant.ASR_PTT, "1");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mDialog.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mDialog.setParameter(SpeechConstant.ASR_AUDIO_PATH,
                Utils.getMainPath(context) + "speech/speech.wav");

        //3.设置回调接口
        mDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult recognizerResult, boolean isLast) {
//                if (!isLast) {
//                    //解析语音
//                    String result = printResult(recognizerResult);
//                    et_content.setText(result);
//                }
                try {
                    StringBuffer speechTxt = new StringBuffer();
                    speechTxt.append(et_input_remarks.getText());
                    speechTxt.append(printResult(recognizerResult));
                    et_input_remarks.setText(speechTxt.toString());
                    et_input_remarks.setSelection(et_input_remarks.getText().length());//有可能超过长度，
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(SpeechError speechError) {
                ToastUtils.toast(speechError.getPlainDescription(true));
            }
        });
        //4.显示dialog，接收语音输入
        mDialog.show();
        // 也可改写成自己想要的字体效果，重写字体的点击事件
        TextView txt = (TextView) mDialog.getWindow().getDecorView().findViewWithTag("textlink");
        txt.setText("");
    }

    // 用HashMap存储听写结果
    private String printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

//        String sn = null;
//        // 读取json结果中的sn字段
//        try {
//            JSONObject resultJson = new JSONObject(results.getResultString());
//            sn = resultJson.optString("sn");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        mIatResults.put(sn, text);
//
//        StringBuffer resultBuffer = new StringBuffer();
//        for (String key : mIatResults.keySet()) {
//            resultBuffer.append(mIatResults.get(key));
//        }
//        return resultBuffer.toString();
        return text;
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
//        if (EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().unregister(this);
//        }
    }

    public void setLocation(LocationAddress location) {
        if(location==null)return;
        this.location = location;
        //如果是新增
        tv_location.setText(location.getAddress());
    }



    public interface DataFormListener{
        void onCancel();

        void onSave(TaskProject taskProject, SmTask smTask, StatisticsDict caType,
                    StatisticsDict currentLevel,
                    CaDictDataVo dictDataVo,
                    List<CaFile> photos, List<CaFile> videos);
    }
    private DataFormListener dataFormListener;

    public void setDataFormListener(DataFormListener dataFormListener) {
        this.dataFormListener = dataFormListener;
    }

    public void loadData(Activity activity, TaskProject taskProject,
                         SmTask smTask,
                         StatisticsDict caType,
                         StatisticsDict currentLevel,
                         CaForm caForm//如果是新增，这个为空
    ) {
        this.activity = activity;
        this.taskProject = taskProject;
        this.smTask = smTask;
        this.caType = caType;
        this.currentLevel = currentLevel;
        this.caForm = caForm;
        this.dictsOfForm = caForm.getDicts();
        this.data = caForm.getData();
        //页面初始化规则

        if(this.data!=null){
            if("1".equals(this.data.getCjjg())){
                cjjgsffh = "1";
                rb_fh.setChecked(true);
            }else {
                cjjgsffh = "0";
                rb_bfh.setChecked(true);
            }


            et_input_remarks.setText(this.data.getRemarks());//
            tv_location.setText(this.data.getAddress());
        }else {
            cjjgsffh = "1";
            rb_fh.setChecked(true);
            et_input_remarks.setText("");
        }
        List<CaFile> images = null;
        List<CaFile> videos = null;
        if(this.data!=null){
            if(caForm.getFiles()!=null&&caForm.getFiles().size()>0){
                images = Stream.of(caForm.getFiles()).
                        filter(i -> i.getFileType().equals(CaFile.type_image))
                        .map(item->{
                            CaFile caFile = JSON.parseObject(JSON.toJSONString(item),CaFile.class);
                            caFile.setFileId(item.getId());
                            return caFile;
                        }).toList();
                videos = Stream.of(caForm.getFiles()).
                        filter(i -> i.getFileType().equals(CaFile.type_video)).map(item->{
                            CaFile caFileLocal = taskGccjFileDao.findByFileId(item.getId());
                            if(caFileLocal!=null)return caFileLocal;//读取本地缓存
                            AcFileTemp acFileTemp = JSON.parseObject(JSON.toJSONString(item),AcFileTemp.class);
                            CaFile caFile = JSON.parseObject(JSON.toJSONString(acFileTemp),CaFile.class);
                            if(item.getThumb()!=null){
                                CjFile thumb = JSON.parseObject(item.getThumb(),CjFile.class);
                                caFile.setThumb(thumb);
                            }
                            caFile.setFileId(item.getId());
                            return caFile;
                        }).toList();
            }
            if(images==null||images.size()==0){//读取本地缓存
                images = taskGccjFileDao.
                        findByDataIdAndType(this.data.getId(),CaFile.type_image);
            }
            if(videos==null||videos.size()==0){//读取本地缓存
                videos = taskGccjFileDao.
                        findByDataIdAndType(this.data.getId(),CaFile.type_video);
            }
        }
        take_image.loadData(activity,taskProject,smTask,caType,
                currentLevel,this.data,
                images,CaFile.type_image);
        take_video.loadData(activity,taskProject,smTask,caType,
                currentLevel,this.data,
                videos,CaFile.type_video);
    }

    public CaDict getDictByCode(String code){
        return Stream.of(dictsOfForm).filter(i->code.equals(i.getDictCode())).findFirstOrElse(null);
    }

    public void setTakeImageViewListener(GccjTakeImageView.TakeImageViewListener takeImageViewListener) {
        this.take_image.setHcCreateViewListener(takeImageViewListener);
        this.take_video.setHcCreateViewListener(takeImageViewListener);
    }

    public void addPhotoData(CaFile imageBean) {
        take_image.addData(imageBean);
    }

    public void addVideoData(CaFile imageBean) {
        take_video.addData(imageBean);
    }

    public void addAudioData(CaFile imageBean) {
        take_image.addData(imageBean);
    }
}
